
"""
This is the support module for makeing a SRP server with twistd.
"""

from zope.interface import implements

import os.path

from twisted.python              import usage
from twisted.plugin              import IPlugin
from twisted.application.service import IServiceMaker
from twisted.application         import internet

from srp_auth import server

class Options (usage.Options):
    synopsis = '''[options].
    This server provides secure password authentication via the Secure
    Remote Password Protocol version 6a'''
    
    optParameters = [ ['port', 'p', 1234, 'The port number to listen on'],
                      ['database', 'd', '/var/lib/srp_auth/credentials.db', 'Credentials database'] ]

    def postOptions(self):
        if self['database'] is None:
            raise usage.UsageError('Missing required argument: database')
        if not os.path.exists( self['database'] ):
            raise usage.UsageError('Database file does not exist: %s' % self['database'])
        try:
            p = int(self['port'])
            if p < 1 or p > 65534:
                raise usage.UsageError('Invalid port number')
        except ValueError:
            raise usage.UsageError('Invalid port number')
                      

class SrpAuthServiceMaker (object):
    implements(IServiceMaker, IPlugin)
    tapname     = 'srp_auth'
    description = 'Secure Remote Password Server'
    options     = Options

    def makeService(self, options):
        factory = server.SrpAuthFactory( options['database'] )
        return internet.TCPServer( int(options['port']), factory )


serviceMaker = SrpAuthServiceMaker()
